"use strict";

const Controller = require("egg").Controller;

class KnowledgeController extends Controller {
  async index() {
    const { ctx, app } = this;

    const { current, size, title = "", status = "" } = ctx.request.body;

    let sql = " ";

    if (title) {
      sql += `where title = "${title}" `;
    } else if (status) {
      sql += `where status = "${status}" `;
    }

    let limit = ` limit ${(current - 1) * size} , ${size}`;

    const data = await app.mysql.query(
      `select * from knowledge ` + sql + limit
    );

    const total = (
      await app.mysql.query(`select count(*) as count from knowledge` + sql)
    )[0].count;

    ctx.body = {
      code: 1,
      data,
      total,
    };
  }

  async issueKnowledge() {
    const { ctx, app } = this;

    const { id } = ctx.request.body;

    const data = await app.mysql.get("knowledge", { id });

    if (data.status) {
      await app.mysql.update("knowledge", { id, status: 0 });
    } else {
      await app.mysql.update("knowledge", { id, status: 1 });
    }

    ctx.body = {
      code: 1,
      msg: "操作成功",
    };
  }

  async del() {
    const { ctx, app } = this;

    const { id } = ctx.request.body;

    await app.mysql.delete("knowledge", { id });

    ctx.body = {
      code: 1,
      msg: "删除成功",
    };
  }

  async add() {
    const { ctx, app } = this;

    const { title, description, comment, url } = ctx.request.body;

    await app.mysql.insert("knowledge", {
      id: null,
      title,
      description,
      comment,
      url,
    });

    ctx.body = {
      code: 1,
      msg: "操作成功",
    };
  }

  async edit() {
    const { ctx, app } = this;

    const { id, title, description, comment, url } = ctx.request.body;

    await app.mysql.update("knowledge", {
      id,
      title,
      description,
      comment,
      url,
    });

    ctx.body = {
      code: 1,
      msg: "操作成功",
    };
  }
}

module.exports = KnowledgeController;
